// 牧场管理 冯

var express = require('express');
var router = express.Router();
const db = require('../../db/db');

//牧场信息管理

// //获取牧场列表信息
// router.get('/ranchList', (req, res) => {
//   let { pageSize, pageNum } = req.query;

//   // 并且提供默认值，例如每页10条，从第一页开始
//   const parsedPageSize = parseInt(pageSize) || 5;
//   const parsedPageNum = parseInt(pageNum) || 1;
//   const offset = (parsedPageNum - 1) * parsedPageSize;
//   let sql = `select * from nc_pasture limit ${offset}, ${parsedPageSize} `;
//   db.query(sql, (err, result) => {
//     if (err) {
//       res.send({ code: 0, message: '服务器错误' });
//       return;
//     } else if (result.length === 0) {
//       res.send({ code: 0, message: '暂无数据' });
//       return;
//     }
//     //获取总条数
//     db.query(`select count(*) as total from nc_pasture`, (err, countResult) => {
//       if (err) {
//         res.send({ code: 0, message: '获取总条数失败' });
//         return;
//       }
//       res.send({ code: 200, message: '牧场列表查询成功', data: result, total: countResult[0].total });
//     })

//   })
// })

//获取牧场信息详情
router.get('/ranchDetail', (req, res) => {
  let { id } = req.query;
  let sql = `select * from nc_pasture where F_id ='${id}'`;
  console.log(sql);

  db.query(sql, [id], (err, result) => {
    if (err) {
      res.send({ code: 0, message: '服务器错误' });
      return;
    }
    res.send({ code: 200, message: '查询成功', data: result });
  })
})

//新增牧场信息
router.post('/ranchAdd', (req, res) => {
  console.log(1);
  let { name, address, phone, manager, area, circum, introduce } = req.body;
  //id为时间戳
  req.id = Date.now();
  let sql = `insert into nc_pasture(F_id,F_Title,F_Address,F_Phone,F_Head,F_Area,F_Zc,F_Introduce) values('${req.id}','${name}','${address}','${phone}','${manager}','${area}','${circum}','${introduce}')`;
  console.log(sql);
  db.query(sql, (err, result) => {
    if (err || name == '' || address == '' || phone == '' || manager == '' || area == '' || circum == '' || introduce == '') {
      res.send({ code: 0, message: '输入字段有误' });
      return;
    }
    res.send({ code: 200, message: '牧场信息新增成功' });
  })
})

// // 删除牧场信息
// router.post('/ranchDelete', (req, res) => {
//   let { id } = req.body;
//   let sql = `delete from nc_pasture where F_id = '${id}'`;
//   console.log(sql);
//   db.query(sql, (err, result) => {
//     if (err) {
//       res.send({ code: 0, message: '删除失败' });
//       return;
//     } else {
//       res.send({ code: 200, message: '删除成功' });
//     }
//   })
// })

// 修改牧场信息
router.post('/ranchUpdate', (req, res) => {
  let { id, name, address, phone, manager, area, circum, introduce } = req.body;
  let sql = `update nc_pasture set F_Title = '${name}',F_Address = '${address}',F_Phone = '${phone}',F_Head = '${manager}',F_Area = '${area}',F_Zc = '${circum}',F_Introduce = '${introduce}' where F_id = '${id}'`;
  console.log(sql);
  db.query(sql, (err, result) => {
    if (err || name == '' || address == '' || phone == '' || manager == '' || area == '' || circum == '' || introduce == '') {
      res.send({ code: 0, message: '牧场信息修改成功' });
      return;
    } else {
      res.send({ code: 200, message: '牧场信息修改成功' });
    }
  })
})

//模糊查询对于所有字段
router.get('/ranchSearch', (req, res) => {
  let { search, pageSize, pageNum } = req.query;

  // 并且提供默认值，例如每页10条，从第一页开始
  const parsedPageSize = parseInt(pageSize) || 5;
  const parsedPageNum = parseInt(pageNum) || 1;
  const offset = (parsedPageNum - 1) * parsedPageSize;
  let sql;
  if (search) {
    sql = `select * from nc_pasture where F_Title like '%${search}%' or F_Address like '%${search}%' or F_Phone like '%${search}%' or F_Head like '%${search}%' or F_Area like '%${search}%' or F_Zc like '%${search}%' or F_Introduce like '%${search}%' limit ${offset}, ${parsedPageSize}`;
  } else {
    sql = `select * from nc_pasture limit ${offset}, ${parsedPageSize}`;
  }
  console.log(sql);
  db.query(sql, (err, result) => {
    if (err) {
      res.send({ code: 0, message: '服务器错误' });
      return;
    } else if (result.length === 0) {
      res.send({ code: 0, message: '查询无结果或者超过查询' });
      return;
    }
    //获取总条数
    if (search) {
      db.query(`select count(*) as total from nc_pasture  where F_Title like '%${search}%' or F_Address like '%${search}%' or F_Phone like '%${search}%' or F_Head like '%${search}%' or F_Area like '%${search}%' or F_Zc like '%${search}%' or F_Introduce like '%${search}%'`, (err, countResult) => {
        if (err) {
          res.send({ code: 0, message: '获取总条数失败' });
          return;
        }
        res.send({ code: 200, message: '查询成功', data: result, total: countResult[0].total });
      })
    }else{
      db.query(`select count(*) as total from nc_pasture`, (err, countResult) => { 
        if (err) {
          res.send({ code: 0, message: '获取总条数失败' });
          return;
        }
        res.send({ code: 200, message: '查询成功', data: result, total: countResult[0].total });
      })
    }

  })
})

//牧场信息批量删除
router.post('/ranchBatchDelete', (req, res) => {
  let { ids } = req.body;
  console.log(ids);
  if (!ids || ids.length === 0) {
    res.send({ code: 0, message: '请选择要删除的牧场' });
    return;
  }
  if (ids.length > 1) {
    ids = ids.join("','");
  }
  let sql = `delete from nc_pasture where F_id in ('${ids}')`;
  console.log(sql);
  db.query(sql, (err, result) => {
    if (err) {
      res.send({ code: 0, message: '删除失败' });
      return;
    }
    res.send({ code: 200, message: '删除成功' });
  })
})



//养殖舍管理

// //获取养殖舍列表信息
// router.get('/breedList', (req, res) => {
//   let { pageSize, pageNum } = req.query;

//   // 并且提供默认值，例如每页10条，从第一页开始
//   const parsedPageSize = parseInt(pageSize) || 5;
//   const parsedPageNum = parseInt(pageNum) || 1;
//   const offset = (parsedPageNum - 1) * parsedPageSize;
//   let sql = `select h.*,p.F_Title as pasture_Title  from nc_house as h left join nc_pasture as p on h.F_Org_Id=p.F_id limit ${offset}, ${parsedPageSize} `;
//   console.log(sql);
//   db.query(sql, (err, result) => {
//     if (err) {
//       res.send({ code: 0, message: '服务器错误' });
//       return;
//     } else if (result.length === 0) {
//       res.send({ code: 0, message: '暂无数据' });
//       return;
//     }
//     //获取总条数
//     db.query(`select count(*) as total from nc_house`, (err, countResult) => {
//       if (err) {
//         res.send({ code: 0, message: '获取总条数失败' });
//         return;
//       }
//       res.send({ code: 200, message: '牧场列表查询成功', data: result, total: countResult[0].total });

//     })
//   })
// })

//获取养殖舍信息详情
router.get('/breedDetail', (req, res) => {
  let { id } = req.query;
  let sql = `select h.*,p.F_Title as pasture_Title from nc_house as h left join nc_pasture as p on h.F_Org_Id=p.F_id where h.F_id ='${id}'`;
  console.log(sql);

  db.query(sql, [id], (err, result) => {
    if (err) {
      res.send({ code: 0, message: '服务器错误' });
      return;
    }
    res.send({ code: 200, message: '查询成功', data: result });
  })
})

//新增养殖舍信息
router.post('/breedAdd', (req, res) => {
  console.log(1);
  let { name, area, pastureId } = req.body;
  //id为时间戳
  req.id = Date.now();
  //创建时间
  req.createTime = new Date().toISOString().replace('T', ' ').substring(0, 19);
  //判断pastureId在nc_pasture表中是否存在
  let sql1 = `select * from nc_pasture where F_id ='${pastureId}'`;
  console.log(sql1);
  db.query(sql1, (err, result) => {
    if (result.length === 0) {
      res.send({ code: 0, message: '所属牧场不存在' });
      return;
    } else {
      let sql = `insert into nc_house(F_id,F_Title,F_Area,F_Org_Id,F_CreateTime) values('${req.id}','${name}','${area}','${pastureId}','${req.createTime}')`;
      console.log(sql);
      db.query(sql, (err, result) => {
        if (err || name == '' || area == '') {
          res.send({ code: 0, message: '输入字段有误' });
          return;
        }
        res.send({ code: 200, message: '牧场信息新增成功' });
      })
    }
  })
})

// 删除养殖舍信息
router.post('/breedDelete', (req, res) => {
  let { id } = req.body;
  let sql = `delete from nc_house where F_id = '${id}'`;
  console.log(sql);
  db.query(sql, (err, result) => {
    if (err) {
      res.send({ code: 0, message: '删除失败' });
      return;
    } else {
      res.send({ code: 200, message: '删除成功' });
    }
  })
})

// 修改养殖舍信息
router.post('/breedUpdate', (req, res) => {
  let { id, name, area, pastureId } = req.body;
  //判断pastureId在nc_pasture表中是否存在
  let sql1 = `select * from nc_pasture where F_id ='${pastureId}'`;
  console.log(sql1);
  db.query(sql1, (err, result) => {
    if (result.length === 0) {
      res.send({ code: 0, message: '所属牧场不存在' });
      return;
    } else {
      let sql = `update nc_house set F_Title = '${name}',F_Area = '${area}',F_Org_Id = '${pastureId}' where F_id = '${id}'`;
      console.log(sql);
      db.query(sql, (err, result) => {
        if (err || name == '' || area == '') {
          res.send({ code: 0, message: '修改失败' });
          return;
        } else {
          res.send({ code: 200, message: '修改成功' });
        }
      })
    }
  })

})

//模糊查询对于标题名
router.get('/breedSearch', (req, res) => {
  let { search, pageSize, pageNum } = req.query;
    if(!search){
      search = '';
    }
  // 并且提供默认值，例如每页10条，从第一页开始
  const parsedPageSize = parseInt(pageSize) || 5;
  const parsedPageNum = parseInt(pageNum) || 1;
  const offset = (parsedPageNum - 1) * parsedPageSize;

  let sql = `select h.*,p.F_Title as pasture_Title from nc_house as h left join nc_pasture as p on h.F_Org_Id=p.F_id where h.F_Title like '%${search}%' limit ${offset}, ${parsedPageSize}`;
  console.log(sql);
  db.query(sql, (err, result) => {
    if (err) {
      res.send({ code: 0, message: '服务器错误' });
      return;
    } else if (result.length === 0) {
      res.send({ code: 0, message: '查询无结果或者超过查询' });
      return;
    }
    //获取总条数
    db.query(`select count(*) as total from nc_house where F_Title like '%${search}%'`, (err, countResult) => {
      if (err) {
        res.send({ code: 0, message: '获取总条数失败' });
        return;
      }
      res.send({ code: 200, message: '查询成功', data: result, total: countResult[0].total });
    })
  })
})

//养殖舍信息批量删除
router.post('/breedBatchDelete', (req, res) => {
  let { ids } = req.body;
  if (ids.length > 1) {
    ids = ids.join("','");
  }
  let sql = `delete from nc_house where F_id in ('${ids}')`;
  console.log(sql);
  db.query(sql, (err, result) => {
    if (err) {
      res.send({ code: 0, message: '删除失败' });
      return;
    }
    res.send({ code: 200, message: '删除成功' });
  })
})



module.exports = router;